// import './seButton.js'
// import './SeExpand.js'
import leftPanelHTML from './LeftPanel.html'
import 'elix/define/Dialog.js'
import 'elix/define/SelectableButton.js'
import 'elix/define/ProgressSpinner'
import 'elix/define/CarouselWithThumbnails.js';
import CarouselHtml from './carousel.html'
const $id = (id) => document.getElementById(id)
const $qq = (sel) => document.querySelector(sel)
const $qa = (sel) => [...document.querySelectorAll(sel)]
const $click = (element, handler) => {
  element.addEventListener('click', handler)
  element.addEventListener('touchend', handler)
}

/*
 * register actions for left panel
 */
/**
 * @type {module}
 */
class LeftPanel {
  /**
   * @param {PlainObject} svgShow  handler
   */
  constructor(svgShow) {
    this.loadCarouse = false
    this.svgShow = svgShow
  }

  /**
   * This is a common function used when a tool has been clicked (chosen).
   * It does several common things:
   * - Removes the pressed button from whatever tool currently has it.
   * - Adds the the pressed button  to the button passed in.
   * @function this.updateLeftPanel
   * @param {string|Element} button The DOM element or string selector representing the toolbar button
   * @returns {boolean} Whether the button was disabled or not
   */
  updateLeftPanel(button) {
    // if (button.disabled) return false
    // // remove the pressed state on other(s) button(s)
    // $qa('#tools_left *[pressed]').forEach((b) => {
    //   b.pressed = false
    // })
    // // pressed state for the clicked button
    // $id(button).pressed = true
    return true
  }




  clickSelect() {
    if (this.updateLeftPanel('tool_select')) {
      window.parent.showLeftPanel = false
      const event=new CustomEvent('ToEditor');
      window.parent.dispatchEvent(event)
      window.open("./pictool.html", "_self")
    }

  }

  clickImg(img) {
    if (img) {
      this.svgShow.loadSvgChart(img, true)
      this.$dialog.close()
    }
  }



  /**
   *
   * @returns {void}
   */
  async clickOpen() {
    if (this.updateLeftPanel('tool_open')) {
      if(this.loadCarouse){
        this.$dialog.open()
        return
      }
      this.loadCarouse = true
      this.$dialog.open()
      var tmp = document.createElement("template")
      this.$container.innerHTML = ""
      const response = await fetch(`${this.svgShow.url}/svg/graphics/list`)
      const data = (await response.json()).data;
      var temHtml =
        `<elix-carousel-with-thumbnails id="carousel">
            <div class="customArrow" slot="arrowButtonPrevious">↫</div>
            <div class="customArrow" slot="arrowButtonNext">↬</div>`
      var echarts = []
      for (var key in data) {
        if (data[key].length > 0) {
          for (var i = 0; i < data[key].length; i++) {            
            let echart_64 = encodeURIComponent(escape(btoa("echart")))
            if(data[key][i].content.indexOf(echart_64)>-1){
              var ctx = decodeURIComponent(escape(atob(data[key][i].content)))
              var ctx_elem = $(ctx).clone()
              ctx_elem.attr("width",950).attr("height",600).addClass("svg")
              var ctx_but = $(ctx).clone()
              ctx_but.attr("width",60).attr("height",60)
              ctx = `<div id="echartDiv${i}" style="width:950px;height:600px;background-color:#1b334d">` + ctx_elem[0].outerHTML + '</div>'
             
            temHtml +=
              `<elix-selectable-button slot="proxy" class="button">
                <div>${ctx_but[0].outerHTML}</div>
                <span>${data[key][i].title} </span>
             </elix-selectable-button>`
            temHtml +=
              `<div class="divimg" style='cursor:pointer;width:950px;height:600px;'  id='echart${i}'
              title='${data[key][i].title}' data='${key}/${data[key][i].title}' 
              >${ctx}</div>`
            }else{
              temHtml +=
              `<elix-selectable-button slot="proxy" class="button">
                <div><img src='data:image/svg+xml;base64,${data[key][i].content}'/></div>
                <span>${data[key][i].title} </span>
             </elix-selectable-button>`
            temHtml +=
              `<div class="divimg" style='cursor:pointer' 
              title='${data[key][i].title}' data='${key}/${data[key][i].title}'>
              <div id="echartDiv${i}" style="width:950px;height:600px;background-color:#1b334d"><img style='cursor:pointer;width:950px;height:600px;' 
              src='data:image/svg+xml;base64,${data[key][i].content}'/></div></div>`
            }
          }
        }
      }
      temHtml += `</elix-carousel-with-thumbnails>`
      tmp.innerHTML = temHtml
      this.$container.append(tmp.content.cloneNode(true))
      
      this.$loading.style.display = "none"
      var that = this

      $("#carousel").find(".divimg").on("click", function (evt) {
        that.clickImg(evt.currentTarget.getAttribute("data"))
      })

      $("#carousel")[0].shadowRoot.querySelector("#proxyList").style["background-color"] = "#100000"
    }
  }

  /**
   *
   * @returns {void}
   */
  async clickReload() {
    var defHtmls = "";
    if (this.updateLeftPanel('tool_reload')) {
      this.svgShow.reloadSymbol()
    }
  }

  clickLast() {
    if (this.updateLeftPanel('tool_last')) {
      this.svgShow.bindlastpic(this.svgShow)
    }
  }

  clickNext() {
    if (this.updateLeftPanel('tool_next')) {
      this.svgShow.bindnextpic(this.svgShow)
    }
  }

  clickBigger() {
    if (this.updateLeftPanel('tool_bigger')) {
      this.svgShow.bindzoombigger(this.svgShow)
    }
  }

  /**
   *
   * @returns {void}
   */
  clickLitter() {
    if (this.updateLeftPanel('tool_litter')) {
      this.svgShow.bindzoomlitter(this.svgShow)
    }
  }

  clickRecover() {
    if (this.updateLeftPanel('tool_recover')) {
      this.svgShow.bindzoomsoga(this.svgShow)
    }
  }

  /**
   * @type {module}
   */
  add(id, handler) {
    $click($id(id), () => {
      if (this.updateLeftPanel(id)) {
        handler()
      }
    })
  }

  /**
   * @type {module}
   */
  init() {
    // add Left panel
    const template = document.createElement('template')
    template.innerHTML = leftPanelHTML
    this.svgShow.$svgShow.append(template.content.cloneNode(true))
    var temp = document.createElement('template')
    temp.innerHTML = CarouselHtml
    // carousel.append(temp.content.cloneNode(true))

    this.svgShow.$svgShow.append(temp.content.cloneNode(true))
    // register actions for left panel
    this.$dialog = this.svgShow.$svgShow.querySelector("#export_box")
    this.$loading = this.svgShow.$svgShow.querySelector("#loading")
    this.$container = this.svgShow.$svgShow.querySelector("#container")
    this.$close = this.svgShow.$svgShow.querySelector('.close')
    var that = this
    $click(this.$close, function () {
      that.$dialog.close()
    })
    $click($id('tool_select'), this.clickSelect.bind(this))
    $click($id('tool_open'), this.clickOpen.bind(this))
    $click($id('tool_reload'), this.clickReload.bind(this))
    $click($id('tool_last'), this.clickLast.bind(this))
    $click($id('tool_next'), this.clickNext.bind(this))
    $click($id('tool_bigger'), this.clickBigger.bind(this))
    $click($id('tool_litter'), this.clickLitter.bind(this))
    $click($id('tool_recover'), this.clickRecover.bind(this))
    $('#tools_left').on('click', '.Shrink', function (e) {
      e.preventDefault();
      e.stopPropagation();
      $(this).toggleClass('active');
      if ($(this).hasClass('active')) {
        $(this).siblings().hide();
      } else {
        $(this).siblings().show();
      }

    });
  }
}

export default LeftPanel
